package com.ptadmin.report.executor.processor;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.UUID;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.ptadmin.report.postgresql.PostgreSqlHelper;

public class DepartmentPGProcessor {
	
	JsonParser parser = new JsonParser();
	
	public void process(ProcessReportsParameter param) {
		JsonReader reader;
		PostgreSqlHelper sqlHelper = new PostgreSqlHelper();
		try {
			reader = new JsonReader(new FileReader("departments_201907100900_15627637028339925"));
			JsonArray departmentJsonArray = parser.parse(reader).getAsJsonArray();
			String sql = "INSERT INTO \"amzStoreDepartment\" (\"departmentId\", \"departmentName\", \"departmentNameCN\") "
					+ "VALUES ";
			String sql2 = "INSERT INTO \"amzStoreDepartmentRootNode\" (\"rootNodeId\", \"departmentId\", \"rootNodeName\", \"rootNodeNameCN\") "
					+ "VALUES ";
			for (JsonElement e1 : departmentJsonArray) {
				JsonObject departmentJson = (JsonObject) e1;
				// System.out.println(departmentJson.get("department").getAsString());
				String departmentId = UUID.randomUUID().toString();
				String departmentName = departmentJson.get("department").getAsString().replace('\'', '`');

				String sql_value = sql + "('" + departmentId + "', '" + departmentName + "', '' );";
				sqlHelper.executeSqlString(sql_value);

				if (departmentJson.get("children_nodes") != null) {
					JsonArray childrenNodesArray = departmentJson.get("children_nodes").getAsJsonArray();
					String sql_value2 = "";
					for (JsonElement e2 : childrenNodesArray) {
						JsonObject nodeJson = (JsonObject) e2;
						String nodeId = nodeJson.get("node_id").getAsString();
						String nodeName = nodeJson.get("node_name").getAsString().replace('\'', '`');
						sql_value2 += "('" + nodeId + "', '" + departmentId + "', '" + nodeName + "', '' ),";

					}
					sql_value2 = sql_value2.substring(0, sql_value2.length() - 1) + ";";
					sql_value2 = sql2 + sql_value2;
					sqlHelper.executeSqlString(sql_value2);
				}
				System.out.println(
						String.format("Opened database successfully, finished insert department: %s", departmentName));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String... args) {
		ProcessReportsParameter param = new ProcessReportsParameter();
		param.setMerchantId("test");
		param.setReportCategory("department");
		param.setReportFilePath("departments_201907100900_15627637028339925");
		param.setReportName("department");
		
		DepartmentPGProcessor processor = new DepartmentPGProcessor();
		processor.process(param);
	}
}
